package com.ipad.ui.activity;

import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.cooltechworks.views.shimmer.ShimmerRecyclerView;
import com.google.zxing.WriterException;
import com.ipad.R;
import com.ipad.bean.Delivery;
import com.ipad.bean.Product;
import com.ipad.bean.Warehouse;
import com.ipad.net.entity.DeliveryContainerEntity;
import com.ipad.net.entity.DeliveryCount;
import com.ipad.net.entity.DeliveryListEntity;
import com.ipad.net.entity.DeliveryListInfoEntity;
import com.ipad.net.presenter.StroePresenter;
import com.ipad.net.view.IStoreView;
import com.ipad.ui.BaseActivity;
import com.ipad.ui.adapter.DeliveryInfoAdapter;
import com.ipad.ui.adapter.DeliveryListAdapter;
import com.ipad.ui.fragmen.ChoosTimeFragment;
import com.ipad.ui.fragmen.ImgDialogFragment;
import com.ipad.ui.fragmen.WarehousV2Fragment;
import com.ipad.utils.MCodeUtils;
import com.ipad.utils.SharePerenceUtils;
import com.ipad.utils.ToasUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.uuzuche.lib_zxing.encoding.EncodingHandler;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class DeliveryRecordActivity extends BaseActivity implements IStoreView, ChoosTimeFragment.SelectTime, WarehousV2Fragment.OnSelectWarehouse {
    @BindView(R.id.delivery_refresh)
    RefreshLayout delivery_refresh;
    @BindView(R.id.delivery_info_refresh)
    RefreshLayout delivery_info_refresh;
    @BindView(R.id.delivery_back)
    ImageView delivery_back;
    @BindView(R.id.delivery_toolbar)
    Toolbar delivery_toolbar;
    @BindView(R.id.delivery_search)
    EditText delivery_search;
    @BindView(R.id.delivery_list)
    ListView delivery_list;
    @BindView(R.id.delivery_img_code)
    ImageView delivery_img_code;
    @BindView(R.id.delivery_bill_code)
    TextView delivery_bill_code;
    @BindView(R.id.delivery_req_store)
    TextView delivery_req_store;
    @BindView(R.id.delivery_total_num)
    TextView delivery_total_num;
    @BindView(R.id.delivery_receiver)
    TextView delivery_receiver;
    @BindView(R.id.delivery_receive_time)
    TextView delivery_receive_time;
    @BindView(R.id.delivery_creater)
    TextView delivery_creater;
    @BindView(R.id.delivery_select_warehouse)
    TextView delivery_select_warehouse;
    @BindView(R.id.recorde_choose_time)
    TextView recorde_choose_time;
    @BindView(R.id.delivery_list_info)
    RecyclerView delivery_list_info;

    List<Delivery> deliveries = new ArrayList<>();
    DeliveryListAdapter deliveryListAdapter;

    List<Product> details = new ArrayList<>();
    DeliveryInfoAdapter deliveryInfoAdapter;

    StroePresenter stroePresenter;

    int details_page = 1;
    int details_total_page = 1;

    int page = 1;
    int rows = 10;
    String out_warehouse_id = "";
    String req_warehouse_id = "";
    String bill_code = "";
    private String TAG = "delivery";
    private int mPosition = 0;
    String end_receive_time = "";
    String start_receive_time = "";
    private String status = "2"; //1已出库 2 已入库 3拒收

    @Override
    public int getLayoutId() {
        return R.layout.activity_delivery_record;
    }

    @Override
    public void initView() {
        recorde_choose_time.setText("至");
        delivery_list_info.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        deliveryInfoAdapter = new DeliveryInfoAdapter(details, this);
        delivery_list_info.setAdapter(deliveryInfoAdapter);


        delivery_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (deliveryListAdapter.getChecked_position() == position) {
                    return;
                }

                delivery_receive_time.setText(deliveries.get(position).getReceiveTime());
                delivery_creater.setText(deliveries.get(position).getCreateName());
                //
                try {
                    BigDecimal total = deliveries.get(position).getOutQuantity().add(deliveries.get(position).getInQuantity());
                    delivery_total_num.setText(total.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                deliveryListAdapter.setChecked_position(position);
                //选择配送单
                MCodeUtils.setOneCodeImage(deliveries.get(position).getBillCode(), delivery_img_code, DeliveryRecordActivity.this);
                delivery_bill_code.setText(deliveries.get(position).getBillCode());
                delivery_req_store.setText(deliveries.get(position).getReqWarehouseName());

                details.clear();
                deliveryInfoAdapter.notifyDataSetChanged();
                details_page = 1;
                details_total_page = 1;
                mPosition = position;
                Log.e(TAG, "onItemClick: " + deliveries.get(position).getId());
                getDeliveryDetail(deliveries.get(position).getId() + "");
            }
        });
        delivery_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                bill_code = s.toString();
                deliveries.clear();
                deliveryListAdapter.notifyDataSetChanged();
                getDeliveryList(bill_code);
            }
        });
        delivery_select_warehouse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                WarehousV2Fragment warehousV2Fragment = WarehousV2Fragment.newInstance(1);
                warehousV2Fragment.show(getSupportFragmentManager(), "");
            }
        });
        delivery_img_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (delivery_img_code.getDrawable() == null || delivery_bill_code.getText().toString() == null || delivery_bill_code.getText().toString().equals("")) {
                    return;
                }
                ImgDialogFragment imgDialogFragment = ImgDialogFragment.newInstance(delivery_bill_code.getText().toString());
                imgDialogFragment.show(getSupportFragmentManager(), "");
            }
        });

        delivery_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        recorde_choose_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ChoosTimeFragment choosTimeFragment = ChoosTimeFragment.newInstance();
                choosTimeFragment.show(getSupportFragmentManager(), "");
            }
        });

        //刷新
        delivery_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                resetDetailsUI();
                mPosition = 0;

                start_receive_time = "";
                end_receive_time = "";
                recorde_choose_time.setText("至");


                deliveryListAdapter.setChecked_position(-1);
                deliveries.clear();
                deliveryListAdapter.notifyDataSetChanged();
                page = 1;
                getDeliveryList(bill_code);


            }
        });
        delivery_refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                page++;
                getDeliveryList(bill_code);
            }
        });
        delivery_info_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                details.clear();
                deliveryInfoAdapter.notifyDataSetChanged();
                details_page = 1;
                details_total_page = 1;

                try {
                    getDeliveryDetail(deliveries.get(mPosition).getId() + "");
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        delivery_info_refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                if (details_page < details_total_page) {
                    details_page++;
                    getDeliveryDetail(deliveries.get(mPosition).getId() + "");
                }
                delivery_info_refresh.finishLoadMore();
            }
        });

    }

    @Override
    public void initData() {
        out_warehouse_id = SharePerenceUtils.getWarehouseId(this);

        stroePresenter = new StroePresenter();
        stroePresenter.attchView(this);

        deliveryListAdapter = new DeliveryListAdapter(deliveries, this);
        delivery_list.setAdapter(deliveryListAdapter);

        getDeliveryList(bill_code);
    }

    public void getDeliveryList(String bill_code) {
        if (stroePresenter != null) {
            stroePresenter.getDeliveryList(bill_code, "", end_receive_time, "0", req_warehouse_id, "", start_receive_time, status, out_warehouse_id, page + "", rows + "", SharePerenceUtils.getToken(this), false);
        }
    }

    public void getDeliveryDetail(String id) {
        if (stroePresenter != null) {
            stroePresenter.getDeliveryDetails(id, details_page + "", rows + "", SharePerenceUtils.getToken(this), false);
        }
    }

    @Override
    public void setToolbar() {
        setSupportActionBar(delivery_toolbar);
    }

    @Override
    public void stopLoading() {
        if (delivery_refresh.isLoading()) {
            delivery_refresh.finishLoadMore();
        }
        if (delivery_refresh.isRefreshing()) {
            delivery_refresh.finishRefresh();
        }
        if (delivery_info_refresh.isLoading()) {
            delivery_info_refresh.finishLoadMore();
        }
        if (delivery_info_refresh.isRefreshing()) {
            delivery_info_refresh.finishRefresh();
        }
    }

    @Override
    public void loading(String msg) {

    }

    @Override
    public void error(String msg) {
        ToasUtils.getToast(msg, this);
    }

    @Override
    public void getDeliveryListSuccess(DeliveryListEntity deliveryListEntity) {
        Log.e(TAG, "getDeliveryListSuccess: ");
        if (deliveryListEntity != null) {
            if (deliveryListEntity.getRecords() != null && deliveryListEntity.getRecords().size() != 0) {
                deliveries.addAll(deliveryListEntity.getRecords());


            }
        }
        deliveryListAdapter.notifyDataSetChanged();
    }

    @Override
    public void getDeliveryDetailSuccess(DeliveryListInfoEntity deliveryListInfoEntity) {
        if (deliveryListInfoEntity != null) {
            if (deliveryListInfoEntity.getRecords() != null && deliveryListInfoEntity.getRecords().size() != 0) {
                details.addAll(deliveryListInfoEntity.getRecords());
                details_total_page = deliveryListInfoEntity.getPages();
            }
        }
        deliveryInfoAdapter.notifyDataSetChanged();
    }

    @Override
    public void getDeliveryCountSuccess(DeliveryCount count) {

    }

    @Override
    public void getDeliveryByContainerSuccess(DeliveryContainerEntity count) {

    }

    @Override
    public void selectTime(String start_time, String end_time) {
        Log.e(TAG, "selectTime: " + start_time + "" + end_time);
        start_receive_time = start_time;
        end_receive_time = end_time;
        recorde_choose_time.setText(start_time + "至" + end_time);


        mPosition = 0;
        resetDetailsUI();

        deliveries.clear();
        deliveryListAdapter.notifyDataSetChanged();
        page = 1;
        getDeliveryList(bill_code);

    }

    public void resetDetailsUI() {
        delivery_bill_code.setText("");
        delivery_req_store.setText("");
        delivery_receive_time.setText("");
        delivery_total_num.setText("");
        delivery_creater.setText("");
        delivery_img_code.setImageResource(0);
        details_page = 1;
        details_total_page = 1;

        req_warehouse_id = "";
        delivery_select_warehouse.setText(getResources().getString(R.string.delivery_select_warehouse));


        details.clear();
        deliveryInfoAdapter.notifyDataSetChanged();
    }

    @Override
    public void selectWarehouse(Warehouse warehouse) {
        req_warehouse_id = warehouse.getId() + "";
        delivery_select_warehouse.setText(warehouse.getName());

        deliveries.clear();
        deliveryListAdapter.notifyDataSetChanged();
        details.clear();
        deliveryInfoAdapter.notifyDataSetChanged();

        getDeliveryList(bill_code);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.delivery_status_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        resetDetailsUI();
        bill_code = "";
        deliveries.clear();
        deliveryListAdapter.notifyDataSetChanged();
        page = 1;

        switch (item.getItemId()){
            //1已出库 2 已入库 3拒收
            case R.id.toBeStorage:
                status = "1";
                getDeliveryList(bill_code);
                break;
            case R.id.hasStoraged:
                status = "2";
                getDeliveryList(bill_code);
                break;
            case R.id.refuse:
                status = "3";
                getDeliveryList(bill_code);
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
